package net.biancheng.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import net.biancheng.common.constant.CommonConstant;
import net.biancheng.common.core.bean.TreeSelect;
import net.biancheng.exception.ServiceException;
import net.biancheng.common.utils.DateUtils;
import net.biancheng.common.utils.SecurityUtils;
import net.biancheng.bean.SysMenu;
import net.biancheng.bean.vo.MetaVo;
import net.biancheng.bean.vo.RouteVo;
import net.biancheng.mapper.SysMenuMapper;
import net.biancheng.mapper.SysRoleMenuMapper;
import net.biancheng.service.ISysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 菜单权限Service业务层处理
 * 
 * @author lb
 * @date 2023-08-03
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService
{
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 查询菜单权限
     * 
     * @param id 菜单权限ID
     * @return 菜单权限
     */
    @Override
    public SysMenu selectSysMenuById(Long id)
    {
        return sysMenuMapper.selectSysMenuById(id);
    }

    /**
     * 查询菜单权限列表
     * 
     * @param sysMenu 菜单权限
     * @return 菜单权限
     */
    @Override
    public List<SysMenu> selectSysMenuList(SysMenu sysMenu)
    {
        List<SysMenu> menuList = null;
        Long userId = SecurityUtils.getUserId();
        // 管理员显示所有菜单信息
        if (SecurityUtils.isAdmin(userId))
        {
            menuList = sysMenuMapper.selectSysMenuList(sysMenu);
        }
        else
        {
            sysMenu.getParams().put("userId", userId);
            menuList = sysMenuMapper.selectSysMenuListByUserId(sysMenu);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询菜单权限列表
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectSysMenuTreeByUserId(Long userId)
    {
        List<SysMenu> menus = null;
        //查询菜单类型 (目录+菜单)
        List<String> menuTypeList = new ArrayList<>();
        menuTypeList.add(CommonConstant.TYPE_DIR);
        menuTypeList.add(CommonConstant.TYPE_MENU);
        //list转逗号分隔字符串，每个字符前后带单引号
        String menuTypes = menuTypeList.stream().map(t -> "'"+t+"'").collect(Collectors.joining(","));
        if (SecurityUtils.isAdmin(userId))
        {
            menus = sysMenuMapper.selectSysMenuAll(menuTypes);
        }
        else
        {
            menus = sysMenuMapper.selectSysMenuByUserId(userId, menuTypes);
        }
        return getSysMenuTreeChild(menus, 0);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectSysMenuPermsByUserId(Long userId)
    {
        List<String> perms = sysMenuMapper.selectSysMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 构建前端所需树结构菜单
     * @param menus
     * @return
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus){
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        //将所有菜单ID存入临时集合，用于后面判断是否是顶级节点
        for (SysMenu menu: menus){
            tempList.add(menu.getId());
        }
        //遍历处理菜单子节点
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();){
            SysMenu menu = iterator.next();
            //判断当前菜单父节点是否是顶级节点
            //不存在则是顶级节点，遍历该父节点的所有子节点
            if(!tempList.contains(menu.getParentId())){
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()){
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需下拉树选择菜单结构
     * @param menus
     * @return
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus){
        List<SysMenu> treeList = buildMenuTree(menus);
        return treeList.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouteVo> buildRouterMenus(List<SysMenu> menus) {
        List<RouteVo> routes = new LinkedList<>();
        for (SysMenu menu: menus){
            RouteVo route = new RouteVo();
            route.setName(getRouterName(menu));
            route.setPath(getRouterPath(menu));
            route.setHidden("1".equals(menu.getVisible()));
            route.setComponent(getComponent(menu));
            route.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && CommonConstant.TYPE_DIR.equals(menu.getMenuType())){//目录类型
                route.setAlwaysShow(true);
                route.setRedirect("noRedirect");
                route.setChildren(buildRouterMenus(cMenus));
            }else if (isFirstMenu(menu)){//一级菜单
                route.setMeta(null);
                List<RouteVo> childrenList = new ArrayList<>();
                RouteVo children = new RouteVo();
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                childrenList.add(children);
                route.setChildren(childrenList);
            }
            routes.add(route);
        }

        return routes;
    }

    /**
     * 新增菜单权限
     * 
     * @param sysMenu 菜单权限
     * @return 结果
     */
    @Override
    public int insertSysMenu(SysMenu sysMenu)
    {
        sysMenu.setCreateTime(DateUtils.getNowDate());
        sysMenu.setCreateBy(SecurityUtils.getUsername());
        return sysMenuMapper.insertSysMenu(sysMenu);
    }

    /**
     * 修改菜单权限
     * 
     * @param sysMenu 菜单权限
     * @return 结果
     */
    @Override
    public int updateSysMenu(SysMenu sysMenu)
    {
        sysMenu.setUpdateTime(DateUtils.getNowDate());
        sysMenu.setUpdateBy(SecurityUtils.getUsername());
        return sysMenuMapper.updateSysMenu(sysMenu);
    }

    /**
     * 删除菜单权限对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysMenuByIds(Long[] ids)
    {
        return sysMenuMapper.deleteSysMenuByIds(ids);
    }

    /**
     * 删除菜单权限信息
     * 
     * @param id 菜单权限ID
     * @return 结果
     */
    @Override
    public int deleteSysMenuById(Long id)
    {
        //判断当前菜单是否存在子级，存在不允许删除
        if (sysMenuMapper.hasChildByParentId(id) > 0)
        {
            throw new ServiceException("存在子菜单,不允许删除");
        }
        //判断当前菜单是否已分配给角色，已分配不允许删除
        if (sysRoleMenuMapper.checkMenuExistRole(id) > 0)
        {
            throw new ServiceException("菜单已分配,不允许删除");
        }

        return sysMenuMapper.deleteSysMenuById(id);
    }

    /**
     * 根据父节点的ID获取树形结构及所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getSysMenuTreeChild(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param m
     */
    private void recursionFn(List<SysMenu> list, SysMenu m)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, m);
        m.setChildren(childList);
        for (SysMenu mChild : childList)
        {
            if (hasChild(list, mChild))
            {
                recursionFn(list, mChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu m)
    {
        List<SysMenu> mlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == m.getId().longValue())
            {
                mlist.add(n);
            }
        }
        return mlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu m)
    {
        return getChildList(list, m).size() > 0;
    }


    /**
     * 获取路由名称
     * @param menu
     * @return
     */
    public String getRouterName(SysMenu menu){
        String routerName = StringUtils.capitalize(menu.getPath()); //首字母转为大写
        if (isFirstMenu(menu)){
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由路径
     * @param menu
     * @return
     */
    public String getRouterPath(SysMenu menu){
        String routerPath = menu.getPath();
        // 一级目录
        if(menu.getParentId().intValue() == 0 && CommonConstant.TYPE_DIR.equals(menu.getMenuType())){
            routerPath = "/" + menu.getPath();
        }
        //一级菜单
        else if(isFirstMenu(menu)){
            routerPath = "/";
        }
        return routerPath;
    }

    public String getComponent(SysMenu menu){
        String component = CommonConstant.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isFirstMenu(menu)){//下级菜单
            component = menu.getComponent();
        }else if(StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)){//二级存在子级的目录菜单
            component = CommonConstant.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 判断是否为parent_view组件（目录下存在子菜单的二级目录菜单） 如：系统管理-日志管理（登录日志、操作日志）
     * @param menu
     * @return
     */
    public boolean isParentView(SysMenu menu){
        return menu.getParentId().intValue() != 0 && CommonConstant.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 判断是否为菜单(一级菜单)
     * @param menu
     * @return
     */
    public boolean isFirstMenu(SysMenu menu){
        return menu.getParentId().intValue() == 0 && CommonConstant.TYPE_MENU.equals(menu.getMenuType());
    }

}